package top.zywork.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import top.zywork.annotation.ReturnBean;
import top.zywork.common.BeanUtils;
import top.zywork.enums.ResponseStatusEnum;
import top.zywork.vo.PagerVO;
import top.zywork.vo.ResponseStatusVO;

/**
 * 在controller方法中指定@ReturnBean注解后，对返回值进行过滤处理<br />
 * 创建于2020-01-15<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@Component
@Aspect
public class ReturnBeanAspect {

    @Pointcut("@annotation(top.zywork.annotation.ReturnBean)")
    public void methodAspect() {}

    @Around("methodAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();
        if (result instanceof ResponseStatusVO) {
            ResponseStatusVO responseStatusVO = (ResponseStatusVO) result;
            if (responseStatusVO.getCode() == ResponseStatusEnum.OK.getCode().intValue()) {
                // 如果返回结果正常
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                ReturnBean returnBean = signature.getMethod().getDeclaredAnnotation(ReturnBean.class);
                Class<?> returnClazz = returnBean.value();
                Object resultObj = responseStatusVO.getData();
                if (resultObj instanceof PagerVO) {
                    // 分页数据对象集合
                    responseStatusVO.setData(BeanUtils.copyList(((PagerVO) resultObj).getRows(), returnClazz));
                } else {
                    // 单个对象
                    responseStatusVO.setData(BeanUtils.copy(resultObj, returnClazz));
                }
                return responseStatusVO;
            }
        }
        return result;
    }

}